/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Logger from '../common/utils/Logger'
import IdlOtaServiceProxy from '../service/data/idl_ota_service_proxy'


const BUNDLE_NAME = "hra.hmos.ota"
const SERVICE_EXTENSION_ABILITY_NAME = "OtaServiceAbility"
const ERROR_CODE = -1 // 失败
const SUCCESS_CODE = 0 // 成功

const TAG: string = "HomeFeature"

export default class HomeFeature {
    connection = -1 // 初始值
    remoteCallback = null
    context = null
    options = null
    otaProxy = null

    constructor(context) {
        this.context = context
        this.options = {
            outObj: this,
            // 连接成功时回调
            onConnect: function (elementName, proxy) {
                Logger.debug(TAG, `onConnect success:${proxy}`)
                // 接收来自服务返回的实例
                if (proxy) {
                    this.outObj.otaProxy = new IdlOtaServiceProxy(proxy)
                    this.outObj.remoteCallback(SUCCESS_CODE)
                } else {
                    this.outObj.remoteCallback(ERROR_CODE)
                }
            },
            onDisconnect: function () {
                Logger.debug(TAG, `onDisconnect`)
            },
            onFailed: function () {
                Logger.debug(TAG, `onFailed`)
            }
        }
    }

    /**
     * 获取检查新版本的结果
     * @returns 有新版本 1000；没有新版本：2101
     */
    getCheckNewVersionStatus() {
        return new Promise<number>((resolve) => {
            Logger.debug(TAG, `getCheckNewVersionStatus ${this.otaProxy}`);
            if (this.otaProxy) {
                this.otaProxy.getCheckNewVersionStatus((code: number, revalue: number) => {
                    if (code === SUCCESS_CODE) {
                        resolve(revalue)
                        Logger.debug(TAG, `getCheckNewVersionStatus, this.revalue = ${revalue}`);
                    } else {
                        resolve(ERROR_CODE)
                        Logger.error(TAG, 'getCheckNewVersionStatus fail');
                    }
                })
            } else {
                resolve(ERROR_CODE)
            }
        })
    }

    /**
     * 设置应用当前的状态
     * @param status 应用的状态
     * @returns 设置状态的结果码。成功 0；错误 -1
     */
    setDownloadTaskStatus(status: number) {
        return new Promise<number>((resolve) => {
            Logger.debug(TAG, `setDownloadTaskStatus ${this.otaProxy}`);
            if (this.otaProxy) {
                this.otaProxy.setDownloadTaskStatus(status, (code: number) => {
                    if (code === SUCCESS_CODE) {
                        resolve(SUCCESS_CODE)
                        Logger.debug(TAG, `setDownloadTaskStatus success`);
                    } else {
                        resolve(ERROR_CODE)
                        Logger.error(TAG, 'setDownloadTaskStatus fail');
                    }
                })
            } else {
                resolve(ERROR_CODE)
            }
        })
    }

    /**
     * 连接服务
     * @param callback 连接服务的回调
     */
    connectServiceExtAbility(callback) {
        Logger.debug(TAG, `connectServiceExtAbility`)
        this.remoteCallback = callback
        let want = {
            bundleName: BUNDLE_NAME,
            abilityName: SERVICE_EXTENSION_ABILITY_NAME
        }
        try {
            this.connection = this.context.connectServiceExtensionAbility(want, this.options)
        } catch (err) {
            Logger.error(TAG, `connectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`)
            callback(ERROR_CODE)
        }
        Logger.debug(TAG, `connectServiceExtensionAbility result:${this.connection}`)
    }

    /**
     * 与服务断开连接
     */
    disconnectServiceExtAbility() {
        Logger.debug(TAG, `disconnectServiceExtensionAbility`)
        this.context.disconnectServiceExtensionAbility(this.connection).then((data) => {
            Logger.debug(TAG, `disconnectServiceExtensionAbility success:${JSON.stringify(data)}`)
        }).catch((error) => {
            Logger.error(TAG, `disconnectServiceExtensionAbility failed:${JSON.stringify(error)}`)
        })
        this.otaProxy = null
    }
}